const { useState, useEffect } = React;
const { Button, Flex, Rate, Space, Modal, Input, Tag, List, Select } = antd;

const vars = [
    { type: 'input', name: 'title', label: '项目名称' },
    { 
      type: 'radio', 
      name: 'type', 
      label: '项目类型',
      options: [] // 初始可为空
    },
    { 
      type: 'checkbox',
      name: 'tags',
      label: '项目标签',
      options: ['紧急', '重要', '长期']
    },
    { type: 'switch', name: 'status', label: '启用状态' }
  ]


const Prompter = () => {
  const [prompts, setPrompts] = useState([]);
  const [visible, setVisible] = useState(false);
  const [editingPrompt, setEditingPrompt] = useState(null);
  const [editingPromptVars, setEditingPromptVars] = useState([]);
  const [editingPromptOpts, setEditingPromptOpts] = useState([]);

  const [formVisible, setFormVisible] = useState(false);

  useEffect(() => {
    loadPrompts();
  }, []);

  const loadPrompts = async () => {
    const allPrompts = await db.prompts.toArray();
    setPrompts(allPrompts);
  };

  const handleSubmit = async (values) => {
    if (editingPrompt) {
      await db.prompts.update(editingPrompt.id, values);
    } else {
      await db.prompts.add(values);
    }
    loadPrompts();
    setVisible(false);
    setEditingPrompt(null);
  };

  const handleDelete = async (id) => {
    await db.prompts.delete(id);
    loadPrompts();
  };

  const handleOptSubmit = async (data) =>{
    prn('data', data)

    editingPrompt.opts = data
    await db.prompts.update(editingPrompt.id, editingPrompt);
  }

  return (
    <div style={{ padding: 20 }}>
      <div style={{ marginBottom: 16 }}>
        <Button type="primary" onClick={() => setVisible(true)}>
          Create Prompt
        </Button>
      </div>
      
      <PromptList
        prompts={prompts}
        onEdit={(record) => {
          setEditingPrompt(record);
          setVisible(true);
        }}
        onOptEdit={(record) => {
          setEditingPrompt(record);
          setFormVisible(true);

          let vars = record.vars.map(it=>{
            it.label = it.name
            return it
          })
  

          let opts = record.opts.options
          setEditingPromptVars(vars)
          setEditingPromptOpts(opts)
          prn(record)
        }}
        onDelete={handleDelete}
      />
      
      <PromptForm
        visible={visible}
        onCancel={() => {
          setVisible(false);
          setEditingPrompt(null);
        }}
        onSubmit={handleSubmit}
        initialValues={editingPrompt}
      />

<OptForm
  vars ={editingPromptVars}
  opts = {editingPromptOpts}
  visible={formVisible}
  onCancel={() => setFormVisible(false)}
  onSubmit={handleOptSubmit}  
/>
    </div>
  );
};